package cn.lblbc.webbrowser

import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.viewpager2.widget.ViewPager2
import cn.lblbc.webbrowser.adapters.ImageViewerAdapter
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

class ImageViewerActivity : BaseActivity() {
    
    private lateinit var viewPager: ViewPager2
    private lateinit var backButton: ImageButton
    private lateinit var favoriteButton: ImageButton
    private lateinit var imageCountText: TextView
    private lateinit var adapter: ImageViewerAdapter
    
    private var imageFiles: List<File> = emptyList()
    private var currentPosition: Int = 0
    private lateinit var favoritesDir: File
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置沉浸式全屏模式
        setupImmersiveMode()
        
        setContentView(R.layout.fragment_image_viewer)
        
        viewPager = findViewById(R.id.imageViewPager)
        backButton = findViewById(R.id.backButton)
        favoriteButton = findViewById(R.id.favoriteButton)
        imageCountText = findViewById(R.id.imageCountText)
        
        // 初始化收藏目录
        favoritesDir = File(getExternalFilesDir(null), "favorites")
        if (!favoritesDir.exists()) {
            favoritesDir.mkdirs()
        }
        
        imageFiles = intent.getSerializableExtra("image_files") as? List<File> ?: emptyList()
        currentPosition = intent.getIntExtra("current_position", 0)
        
        setupViewPager()
        updateImageCount()
        updateFavoriteButton()
        
        backButton.setOnClickListener {
            finish()
        }
        
        favoriteButton.setOnClickListener {
            toggleFavorite()
        }
    }
    
    private fun setupViewPager() {
        adapter = ImageViewerAdapter(imageFiles)
        viewPager.orientation = ViewPager2.ORIENTATION_VERTICAL
        viewPager.adapter = adapter
        viewPager.setCurrentItem(currentPosition, false)
        
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPosition = position
                updateImageCount()
                updateFavoriteButton()
            }
        })
    }

    private fun updateImageCount() {
        if (imageFiles.isNotEmpty()) {
            imageCountText.text = "${currentPosition + 1} / ${imageFiles.size}"
        } else {
            imageCountText.text = "0 / 0"
        }
    }
    
    private fun updateFavoriteButton() {
        if (imageFiles.isNotEmpty() && currentPosition < imageFiles.size) {
            val currentFile = imageFiles[currentPosition]
            val favoriteFile = File(favoritesDir, currentFile.name)
            if (favoriteFile.exists()) {
                favoriteButton.setImageResource(R.drawable.ic_favorite_filled)
            } else {
                favoriteButton.setImageResource(R.drawable.ic_favorite_border)
            }
        }
    }
    
    private fun toggleFavorite() {
        if (imageFiles.isEmpty() || currentPosition >= imageFiles.size) return
        
        val currentFile = imageFiles[currentPosition]
        val favoriteFile = File(favoritesDir, currentFile.name)
        
        try {
            if (favoriteFile.exists()) {
                // 取消收藏
                favoriteFile.delete()
                favoriteButton.setImageResource(R.drawable.ic_favorite_border)
                Toast.makeText(this, "已取消收藏", Toast.LENGTH_SHORT).show()
            } else {
                // 添加收藏
                copyFile(currentFile, favoriteFile)
                favoriteButton.setImageResource(R.drawable.ic_favorite_filled)
                Toast.makeText(this, "已添加到收藏", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "操作失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun copyFile(source: File, destination: File) {
        FileInputStream(source).use { input ->
            FileOutputStream(destination).use { output ->
                input.copyTo(output)
            }
        }
    }
    
    private fun setupImmersiveMode() {
        // 启用边到边显示
        WindowCompat.setDecorFitsSystemWindows(window, false)
        
        // 获取窗口控制器
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        
        // 隐藏状态栏和导航栏
        windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
        
        // 设置系统栏行为：滑动时显示，自动隐藏
        windowInsetsController.systemBarsBehavior = 
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        
        // 设置状态栏和导航栏为透明
        window.statusBarColor = android.graphics.Color.TRANSPARENT
        window.navigationBarColor = android.graphics.Color.TRANSPARENT
    }
    
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            // 重新进入沉浸式模式
            val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
            windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
        }
    }
}